import { ref } from 'vue'
import { 
  industryRatio,
  heatMapData,
  districtRank,
  industryTrends
} from '../mock/mockData'

// 北京市各区坐标数据
const beijingGeoData = {
  type: 'FeatureCollection',
  features: [
    {
      type: 'Feature',
      properties: { name: '东城区' },
      geometry: { 
        type: 'Polygon',
        coordinates: [[
          [116.41, 39.93], [116.42, 39.93], [116.42, 39.92], [116.41, 39.92]
        ]]
      }
    },
    // 其他区数据...
  ]
}
// 获取行业占比数据
export const readIndustryRatio = (year) => {
  console.log('readIndustryRatio');

  const monthlyData = require('../mock/month-alldomain.json');
  const industries = ['power', 'transport', 'industry', 'aerospace', 'consume'];
  const result = [];
  const industryKeyMap = {
  'total': "全部",
  'power': "电力",
  'transport': "运输",
  'aerospace': "航空",
  'industry': "工业",
  'consume': "消费"
}

  industries.forEach(industry => {
    const yearlyData = monthlyData[industry].filter(item => item.month.startsWith(year + '/'));

    let yearCount = 0;
    yearlyData.forEach(item => {
      yearCount += item.CO2;
    });

    result.push({
      name: industryKeyMap[industry],
      value: yearCount
    })
  })  
  // console.log('readIndustryRatio result');

  // console.log(result);
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(result))
    }, 500)
  })
}
// 获取行业占比数据
export const getIndustryRatio = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(industryRatio))
    }, 500)
  })
}

// 获取热力图数据
export const readHeatMapData = (year, industry) => {
  console.log('readHeatMapData ' + year + ' ' + industry);

  const monthlyData = require('../mock/month-alldomain.json');
  const industries = ['total', 'power', 'transport', 'industry', 'aerospace', 'consume'];
  const yearlyData = monthlyData[industry].filter(item => item.month.startsWith(year + '/'));
  let result = [];
  const keys = ['CO2','东城', '西城', '朝阳', '海淀','丰台', '石景山', '门头沟', '房山','通州', '顺义', '昌平', '大兴','怀柔', '平谷', '密云', '延庆']
  let midData = {"CO2": 0,"东城": 0,"西城": 0,"朝阳": 0,"海淀": 0,"丰台": 0,"石景山": 0,"大兴": 0,"通州": 0,"昌平": 0,"门头沟": 0,"房山": 0,"顺义": 0,"平谷": 0,"怀柔": 0,"密云": 0,"延庆": 0}

  yearlyData.forEach(item => {
      keys.forEach(key => {
        midData[key] += item[key]
    })
  });
  result = Object.keys(midData).map(key => ({
    name: key,
    value: midData[key]
  }))

  // console.log(result);

  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(result))
    }, 500)
  })
}
// 获取热力图数据
export const getHeatMapData = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(heatMapData))
    }, 500)
  })
}

// 获取行业趋势数据
export const getIndustryTrend = (industry) => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(industryTrends[industry] || {}))
    }, 500)
  })
}
// 获取行业趋势数据
export const getIndustryTrends = (years, district, industry) => {
    console.log(years)

  const trends = {}
  years.forEach(year => {
    trends[year] = readYearlyDistrictTrendWithoutPromise(year, district)
  });
  console.log('getIndustryTrends by ' + years.join(',') + ' by ' + district + ' by ' + industry)
  console.log(trends);

  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(trends || {}))
    }, 500)
  })
}
// 获取区域排名数据
export const getDistrictRank = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(districtRank))
    }, 500)
  })
}

/**
 * 读取各区域碳排放排名数据
 * @returns {Promise} 返回区域排名数据，格式为[{name: 区域名称, value: 排放量}]
/**
 * 读取年度区域碳排放趋势
 * @param {string} year - 年份，如"2023"
 * @param {string} district - 区域名称，如"海淀"、"全北京"
 * @returns {Promise} 返回月度碳排放趋势数据，格式为[{month, power, transport, industry, aerospace, consume}]
 */
export const readYearlyDistrictTrend = (year, district) => {
  console.log('readYearlyDistrictTrend by ' + year + ' by ' + district);

  const monthlyData = require('../mock/month-alldomain.json');
  const industries = ['total', 'power', 'transport', 'industry', 'aerospace', 'consume'];
  
  // 筛选指定年份的数据
  const yearlyData = monthlyData.total.filter(item => item.month.startsWith(year + '/'));
  
  // 处理数据
  const result = yearlyData.map(monthData => {
    const item = { month: monthData.month.split('/')[1] }; // 只保留月份
    
    // 处理全北京情况
    if (district === '全北京') {
      industries.forEach(industry => {
        if (industry === 'total') {
          item["total"] = monthData.CO2;
        } else {
          item[industry] = monthlyData[industry]?.find(d => d.month === monthData.month)?.CO2 || 0;
        }
      });
    } 
    // 处理具体区域
    else {
      industries.forEach(industry => {
        const industryData = monthlyData[industry]?.find(d => d.month === monthData.month);
        item[industry] = industryData ? industryData[district] || 0 : 0;
      });
    }
    
    return item;
  });
  // console.log(result);

  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(result));
    }, 500);
  });
}

const readYearlyDistrictTrendWithoutPromise = (year, district) => {
  console.log('readYearlyDistrictTrend by ' + year + ' by ' + district);

  const monthlyData = require('../mock/month-alldomain.json');
  const industries = ['total', 'power', 'transport', 'industry', 'aerospace', 'consume'];
  
  // 筛选指定年份的数据
  const yearlyData = monthlyData.total.filter(item => item.month.startsWith(year + '/'));
  
  // 处理数据
  const result = yearlyData.map(monthData => {
    const item = { month: monthData.month.split('/')[1] }; // 只保留月份
    
    // 处理全北京情况
    if (district === '全北京') {
      industries.forEach(industry => {
        if (industry === 'total') {
          item["total"] = monthData.CO2;
        } else {
          item[industry] = monthlyData[industry]?.find(d => d.month === monthData.month)?.CO2 || 0;
        }
      });
    } 
    // 处理具体区域
    else {
      industries.forEach(industry => {
        const industryData = monthlyData[industry]?.find(d => d.month === monthData.month);
        item[industry] = industryData ? industryData[district] || 0 : 0;
      });
    }
    
    return item;
  });
  // console.log(result);
  return result;
}


export const readDistrictRank = () => {
  const yearData = require('../mock/total-year.json');
  const currentYear = new Date().getFullYear();
  
  // 获取当前年份数据(默认取最后一个)
  const targetData = yearData.find(item => item.year === String(currentYear)) || yearData[yearData.length - 1];
  
  // 转换为districtRank格式
  const districtRank = [];
  for (const [name, value] of Object.entries(targetData)) {
    if (name !== 'year' && name !== 'CO2') {
      districtRank.push({ name, value });
    }
  }
  
  // 按排放量降序排序
  return new Promise(resolve => {
    setTimeout(() => {
      resolve(ref(districtRank.sort((a, b) => a.value - b.value)));
    }, 500);
  });
}

export default {
  beijingGeoData,
  getIndustryRatio,
  getHeatMapData,
  getIndustryTrend,
  getDistrictRank,
  getIndustryTrends,
  readHeatMapData,
  readIndustryRatio,
  readDistrictRank,
  readYearlyDistrictTrend
}